package com.conan.exceldemo.service;

import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;

@Service
public class ExcelUtilImp implements ExcelUtil {
    @Override
    public void createExcel(String name) {

        //伪造数据
        String  c1 = "A";
        String  c2 = "a,c,d,b";
        String  c3 = "e,f,g";
        String  c4 = "B";

        String[] c2s = c2.split(",");
        String[] c3s = c3.split(",");

        //计算所需单元格行数
        int rowNum = c2s.length*c3s.length;

        //创建工作簿
        XSSFWorkbook wb = new XSSFWorkbook();
        //创建一个sheet
        XSSFSheet sheet = wb.createSheet();

        // 创建单元格样式
        XSSFCellStyle style =  wb.createCellStyle();
        style.setBorderBottom(BorderStyle.THIN); //底边框加黑
        style.setBorderLeft(BorderStyle.THIN);  //左边框加黑
        style.setBorderRight(BorderStyle.THIN); // 有边框加黑
        style.setBorderTop(BorderStyle.THIN); //上边框加黑
        //为单元格添加背景样式
        for (int i = 0; i < rowNum+4; i++) { //需要表格行数
            Row row =	sheet.createRow(i); //创建行
            for (int j = 0; j < 4; j++) {//需要列数
                row.createCell(j).setCellStyle(style);
            }
        }

        //填入数据
        for (int i = 0;i < c2s.length;i++){
            for (int j = 0; j < c3s.length;j++) {
                XSSFRow row = sheet.getRow(j+i*c3s.length); //获取第i行
                row.getCell(0).setCellValue(c1);
                row.getCell(1).setCellValue(c2s[i]);
                row.getCell(2).setCellValue(c3s[j]);
                row.getCell(3).setCellValue(c4);
            }
        }

        //原表数据
        XSSFRow row = sheet.getRow(rowNum+3); //获取第i行
        row.getCell(0).setCellValue(c1);
        row.getCell(1).setCellValue(c2);
        row.getCell(2).setCellValue(c3);
        row.getCell(3).setCellValue(c4);

        //将数据写入文件
        FileOutputStream out;
        try {
            out = new FileOutputStream(name);
            wb.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
